package com.it.shiro.shiro;


import com.google.gson.Gson;
import com.it.base.resposne.JsonData;
import lombok.Data;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @program: learning
 * @description: 自定义表单认证过滤器
 * @author: Lefnmg
 * @create: 2018-11-12 15:29
 **/
@Data
public class MyFormFilter extends AuthenticatingFilter {
    private String usernameParam = "username";
    private String passwordParam = "password";
    private static final Logger log = LoggerFactory.getLogger(MyFormFilter.class);

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        String username = this.getUsername(request);
        String password = this.getPassword(request);
        return this.createToken(username, password, request, response);
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) {
            return true;
        }

        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = this.getSubject(request, response);
        if (subject.isAuthenticated()) {
            return true;
        } else {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
//            httpResponse.setHeader("Access-Control-Allow-Origin", (HttpServletRequest)request.getHeader("Origin"));
            String json = new Gson().toJson(JsonData.error(401, "未认证"));
            httpResponse.setCharacterEncoding("UTF-8");
            httpResponse.getWriter().print(json);

        }
        return false;
    }

    protected String getUsername(ServletRequest request) {
        return WebUtils.getCleanParam(request, this.getUsernameParam());
    }

    protected String getPassword(ServletRequest request) {
        return WebUtils.getCleanParam(request, this.getPasswordParam());
    }
}
